package de.easywakeup.appService;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import android.content.Context;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import de.easywakeup.data.Data;
import de.easywakeup.yahooWeather.GetWeather;
import de.easywakeup.yahooWeather.GetWoeid;

public class PersistenceHandler
{
	private static Data data;
	private static Context con;

	public PersistenceHandler( Context con, Data data )
	{
		PersistenceHandler.con = con;
		PersistenceHandler.data = data;
	}

	public void saveData( )
	{
		// /*Operating mode. Use 0 or MODE_PRIVATE for the default operation,
		// MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
		// The bit MODE_MULTI_PROCESS can also be used if multiple processes are
		// mutating the same SharedPreferences file. MODE_MULTI_PROCESS is
		// always on in apps targetting Gingerbread (Android 2.3) and below, and
		// off by default in later versions.*/
		// data.setSharedpreferences( getSharedPreferences(Data.MyPREFERENCES,
		// Context.MODE_PRIVATE));

		System.out.println( "SaveData" );
		// convert Datamodel to String
		XStream xstream = new XStream( new DomDriver( ) );
		String xml = xstream.toXML( data );
		// writeFile
		try
		{

			// Open output stream for EasyWakeUpFile
			FileOutputStream fos = con.openFileOutput( "EasyWakeUpFile", Context.MODE_PRIVATE );
			// write data
			fos.write( xml.getBytes( ) );
			// Close output stream
			fos.close( );
		}
		catch( Exception e )
		{
			e.printStackTrace( );
		}
	}

	public void readData( )
	{
		System.out.println( "ReadData" );
		StringBuffer stringBuffer = new StringBuffer( );
		try
		{
			// reads from EasyWakeUpFile
			BufferedReader inputReader = new BufferedReader( new InputStreamReader( con.openFileInput( "EasyWakeUpFile" ) ) );
			String inputString;

			while( ( inputString = inputReader.readLine( ) ) != null )
			{
				stringBuffer.append( inputString + "\n" );
			}

		}
		catch( IOException e )
		{
			System.out.println( "!!!FileNotFoundException!!!" );
		}

		// If the String is null or the File is not existing, it will cancel
		if( stringBuffer.length( ) != 0 )
		{
			XStream xstream = new XStream( new DomDriver( ) );
			Data temp = (Data) xstream.fromXML( stringBuffer.toString( ) );

			data.setData( temp );

			// In the Data AppService, Yahoo Weather task GetWeather and Main
			// Screen Fields declared as transient. These are not stored and are
			// considered as null / empty object by reading. This I have to
			// recreate it.
			Data.setGetWoeid( new GetWoeid( ) );
			Data.setGetWeather( new GetWeather( ) );
		}
		System.out.println( "ReadData" );
	}
}
